import { Ellipsis } from '@/components/Ellipsis';
import {
  delFileInfo,
  downloadFile,
  getFileInfoByPage,
  getFileInfoByPageAndInfoId,
  getFileType,
  getProjectName,
  updateFileInfo,
  uploadFileInfo,
} from '@/services/project/fileInfo';
import { filterTran, sortTran } from '@/utils/requestUtil';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Select, Upload } from 'antd';
import React, { useRef, useState } from 'react';
const FileInfo = React.forwardRef((props, ref) => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [optionsFileAdd, setOptionsFileAdd] = useState([]);
  const [optionsProName, setOptionsProName] = useState([]);
  const [file, setFile] = useState();
  const [infoId, setInfoId] = useState();
  const [form] = Form.useForm();
  const refs = useRef(null);

  React.useImperativeHandle(ref, () => ({
    update() {
      actionRef.current?.reload();
    },
  }));
  FileInfo.defaultProps = {
    /*     infoFlag: true, */ //这里的初始化时什么意思呢？
    infosId: '',
    teamsId: '',
  };
  const infoFlag = props.infoFlag;
  const infosId = props.infosId;
  const teamsId = props.teamsId;

  // // 下载流
  // const downloadSource = (data: any, fileName: any) => {
  //   const blob = new Blob([data], { type: 'application/msword' });
  //   const downloadElement = document.createElement('a');
  //   // 创建下载的链接
  //   const href = window.URL.createObjectURL(blob);
  //   downloadElement.href = href;
  //   // 下载后文件名
  //   downloadElement.download = fileName;
  //   document.body.appendChild(downloadElement);
  //   downloadElement.click();
  //   document.body.removeChild(downloadElement);
  //   // 释放掉blob对象
  //   window.URL.revokeObjectURL(href);
  // };

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      align: 'center',
      width: 50,
      sorter: (a, b) => a - b,
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      width: 90,
      align: 'center',
      render: (text) => <>{Ellipsis(text)}</>,
      sorter: (a, b) => a - b,
    },
    {
      title: '文件名称',
      dataIndex: 'fileName',
      width: 200,
      align: 'center',
      sorter: (a, b) => a - b,
      render: (text, record) => [
        <a
          key="editKey"
          onClick={async () => {
            // const result = await downloadFile(record.id);
            // downloadSource(result, '222');
            // console.log(record.id, 'record.id');
            // console.log('下载文件', result);
            downloadFile(record.id).then((res) => {
              const aLink = document.createElement('a');
              document.body.appendChild(aLink);
              aLink.style.display = 'none';
              aLink.href = window.URL.createObjectURL(res);
              aLink.setAttribute('download', `${record.fileName}`);
              aLink.click();
              document.body.removeChild(aLink);
            });
          }}
        >
          {Ellipsis(record.fileName)}
        </a>,
      ],
    },

    {
      title: '文件类别',
      dataIndex: 'category',
      width: 90,
      sorter: (a, b) => a - b,
      align: 'center',
      valueType: 'select',
      request: async () => optionsFileAdd,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    // {
    //   title: '文件编号',
    //   dataIndex: 'fileCode',
    //   width: 90,
    //  align: 'center',sorter: true,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },
    {
      title: '文件后缀',
      dataIndex: 'fileExtEndDate',
      width: 90,
      sorter: (a, b) => a - b,
      align: 'center',
      search: false,
      render: (text) => <>{Ellipsis(text)}</>,
    },

    {
      title: '文件大小',
      dataIndex: 'fileSize',
      width: 90,
      search: false,
      sorter: (a, b) => a - b,
      align: 'center',
      render: (text) => <div>{Math.floor(text / 1024)}KB</div>,
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
      width: 90,
      align: 'center',
      sorter: (a, b) => a - b,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
      width: 90,
      sorter: (a, b) => a - b,
      align: 'center',
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '备注',
      dataIndex: 'memo',
      search: false,
      sorter: (a, b) => a - b,
      width: 90,
      align: 'center',
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 90,
      align: 'center',
      render: (text, record) => [
        /*         <a //无需编辑按钮
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('编辑');
            form.setFieldsValue({
              basePath: record.basePath,
              category: record.category,
              fileCode: record.fileCode,
              fileData: record.fileData,
              fileExtEndDate: record.fileExtEndDate,
              fileName: record.fileName,
              fileSize: record.fileSize,
              memo: record.memo,
              reserved: record.reserved,
              savePath: record.savePath,
              serialNo: record.serialNo,
              infoId: record.infoId,
              projectName: record.projectName,
              id: record.id,
            });
          }}
        >
          编辑
        </a>, */
        <a
          key="editKey"
          onClick={async () => {
            // const result = await downloadFile(record.id);
            // downloadSource(result, '222');
            // console.log(record.id, 'record.id');
            // console.log('下载文件', result);
            downloadFile(record.id).then((res) => {
              console.log('res', res);
              const aLink = document.createElement('a');
              document.body.appendChild(aLink);
              aLink.style.display = 'none';
              aLink.href = window.URL.createObjectURL(res);
              aLink.setAttribute('download', `${record.fileName}`);
              aLink.click();
              document.body.removeChild(aLink);
            });
          }}
        >
          下载
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delFileInfo({ id: record.id });
                actionRef.current!.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      form
        .validateFields()
        .then(async (value) => {
          if (file == undefined) message.error('请上传文件！');
          if (file.size / 1024 / 1024 < 100) {
            const formData = new window.FormData();
            const res = form.getFieldsValue();
            res.file.fileList.map((file: any) => {
              formData.append('file', file.originFileObj);
            });
            if (infoFlag !== undefined && !infoFlag) {
              res.infoId = infosId;
            } else {
              res.infoId = infoId;
            }
            res.file = formData;
            console.log('附件信息', res);
            const result = await uploadFileInfo(res);
            if (result != null) {
              message.success('添加成功');
            }
            setFile(undefined);
            setConfirmLoading(false);
            setModalVisit(false);
            actionRef.current!.reload();
          } else {
            setConfirmLoading(false);
            message.info('文件大小不能超过100MB!');
          }
          //form.resetFields();
        })
        .catch((err) => {
          setConfirmLoading(false);
        });
    } else {
      form
        .validateFields()
        .then(async () => {
          const res = form.getFieldsValue();
          res.file = new FormData();
          res.infoId = optionsProName.find(
            () => optionsProName.label === form.getFieldsValue.projectName,
          ).value;
          if (file != null) {
            const formData = new window.FormData();
            formData.append('file', file);
            res.file = formData;
          }
          const result = await updateFileInfo(res);
          if (result != null) {
            message.success('修改成功！');
          }
          setConfirmLoading(false);
          setModalVisit(false);
          actionRef.current!.reload();
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    }
  };

  // const checkFileSize = (file: any) => {
  //   console.log(file.size / 1024 / 1024 < 2);
  //   return file.size / 1024 / 1024 < 2;
  //   };

  const onFilesChange = async (file) => {
    setFile(file);
  };

  const beforeUpload = (file, fileList) => {
    setFile(file);
    if (fileList.length >= 1) {
      return false; // 阻止上传
    }
    return true; // 允许上传
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="附件总览查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={refs}
        toolBarRender={
          infoFlag
            ? false
            : (action, { selectedRows }) => [
                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    setCreateOrUpdate(false);
                    setFormTitle('新建');
                    form.resetFields();
                    setModalVisit(true);
                  }}
                  type="primary"
                >
                  新建
                </Button>,
              ]
        }
        request={async (params = {}, sort, filter) => {
          const sorters = sortTran(sort);
          const filters = filterTran(params);
          console.log(infoFlag);
          //两种情况
          let result;
          if (infoFlag === undefined) {
            result = await getFileInfoByPage({ ...params, sorters: sorters, filters: filters });
          } else {
            const fileParams = {
              infoId: infosId,
              pageEntity: {
                current: 1,
                filters: [
                  {
                    andOr: 'and',
                    field: 'teamId',
                    operator: '=',
                    value: teamsId,
                  },
                ],
                pageSize: 20,
                sorters: [],
              },
            };
            result = await getFileInfoByPageAndInfoId(fileParams); //获取附件
          }
          const res = await getFileType(null);
          const typeTemp: any[] = [];
          res.data.map((item: any, index: any) => {
            typeTemp.push({ value: item, label: item });
          });
          setOptionsFileAdd(typeTemp);
          const getProName = await getProjectName(null);
          const value2 = [] as any[];
          getProName.data.map((item: any) => {
            value2.push({ value: item.infoId, label: item.projectName });
          });
          result.data.content.map((item: any) => {
            item.createTime = item.createTime.split(' ')[0];
          });
          console.log(result);
          //对象数组去重
          const uniqueArr = Array.from(
            result.data?.content
              .reduce((map, obj) => {
                if (!map.get(obj.fileName)) {
                  map.set(obj.fileName, obj);
                }
                return map;
              }, new Map())
              .values(),
          );
          console.log(uniqueArr);
          setOptionsProName(value2);
          return {
            data: uniqueArr,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        search={infoFlag}
        columns={columns}
        scroll={{ x: 1200, y: 350 }}
        rowSelection={{}}
      />
      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
        destroyOnClose
      >
        <Form
          encType="multipart/form-data"
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            hidden={!(infoFlag == undefined)}
            label="项目选择"
            name="projectName"
            rules={[{ required: infoFlag === undefined ? true : false }]}
          >
            <Select
              placeholder="请选择项目信息"
              disabled={createOrUpdate}
              onChange={(value) => {
                setInfoId(value);
              }}
              options={optionsProName}
            />
          </Form.Item>
          <Form.Item
            label="文件类别"
            name="category"
            rules={[{ required: true, message: '请选择文件类别！' }]}
          >
            <Select
              placeholder="请选择文件类别"
              //disabled={createOrUpdate}
              onChange={() => {}}
              options={optionsFileAdd}
            />
          </Form.Item>
          <Form.Item
            label="文件上传"
            name="file"
            //name="projectName"
            //rules={[{ required: true, message: '请选择待上传文件！' }]}
          >
            <Upload
              //listType="picture-card"
              file-list="fileList"
              customRequest={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
              showUploadList={true}
              multiple
              beforeUpload={beforeUpload}
            >
              <Button icon={<UploadOutlined />}>上传文件</Button>
            </Upload>
          </Form.Item>

          <Form.Item
            label="备注"
            name="memo"
            //rules={[{ required: true, message: 'Please input your memo!' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
});
export default FileInfo;
